package com.bocai.grainshop.sreach.service.impl;

import com.alibaba.fastjson.JSON;
import com.bocai.common.to.es.SkuEsModel;
import com.bocai.grainshop.sreach.config.ElasticsreachConfig;
import com.bocai.grainshop.sreach.constant.EsConstant;
import com.bocai.grainshop.sreach.service.ElasticSaveProductService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ElasticSaveProductServiceImpl implements ElasticSaveProductService {

    @Resource
    private RestHighLevelClient restHighLevelClient;

    @Override
    public boolean productStatusUp(List<SkuEsModel> skuEsModels) throws IOException {
        //给es中建立索引
        //给es中批量保存这些数据
        BulkRequest bulkRequest = new BulkRequest();
        skuEsModels.forEach(obj->{
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            indexRequest.id(obj.getSkuId().toString());
            String s = JSON.toJSONString(obj);
            indexRequest.source(s,XContentType.JSON);
            bulkRequest.add(indexRequest);
        });
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, ElasticsreachConfig.COMMON_OPITONS);
        //如果发送批量错误
        boolean b = bulk.hasFailures();
        List<String> collect = Arrays.stream(bulk.getItems()).map(obj -> {
            return obj.getId();
        }).collect(Collectors.toList());
        log.info("商品成功",collect);
        return b;
    }
}
